import csv

def get_switch_list(file_path):
    switch_names = []
    with open(file_path, 'r', encoding='GBK') as f:
        reader_list = csv.reader(f)

        for _, row in enumerate(reader_list):
            if row:
                switch_names.append(row)

    return switch_names

def remove_duplicate_ip(switch_names: list):
    results = []

    for i, name in enumerate(switch_names):
        if not name:
            switch_names.pop(i)
        if len(name) > 0:
            if '-' not in name[0]:
                switch_names.pop(i)
                # print(f'warning: remove ip with no name. host: ', name)
    
    for name in switch_names:
        if len(name) == 1:
            results.append(name[0])

    return results

def convert_switch_info(switch_names: list):
    switch_infos = {}

    for switch in switch_names:
        split_switch_name = switch.split('-')
        switch_name_len = len(split_switch_name)
        name, ip = split_switch_name[:switch_name_len - 1], split_switch_name[switch_name_len - 1:][0].strip()
        split_ip = ip.split('.')
        if len(split_ip) == 4:
            ip = '.'.join(split_ip)
        if switch_infos.get(ip):
            # print('重复IP: {} {}'.format(ip, name))
            pass
        else:
            switch_infos[ip] = '-'.join(name)
        # if len(split) == 2:
        #     ip = split[1]
        #     name = split[0]
        #     if not switch_infos.get(ip):
        #         switch_infos[ip] = name
        #     else:
        #         print('重复IP: {} {}'.format(ip, name))
        # elif len(split) == 3:
        #     ip = split[2]
        #     name = '-'.join(split[0:2])
        #     if not switch_infos.get(ip):
        #         switch_infos[ip] = name
        #     else:
        #         print('重复IP: {} {}'.format(ip, name))

    return switch_infos

def get_ips(csv_file):
    r = get_switch_list(csv_file)
    rr = remove_duplicate_ip(r)
    rrr = convert_switch_info(rr)

    return rrr

if __name__ == '__main__':
    csv_file = 'e:\\ips.csv'
    rrr = get_ips(csv_file)
    for n, (k, v) in enumerate(rrr.items()):
        print(n, k, v)
